<template>
  <div class="drift-page">
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" label-width="80px">
        <el-form-item label="巷道名称">
          <el-input
            v-model="searchForm.driftName"
            placeholder="请输入巷道名称"
            clearable
            style="width: 260px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

   

    <!-- 列表区域 -->
    <el-card class="table-card">
      <div style="margin-bottom: 10px;">
        <el-button type="primary" @click="openDialog">新增</el-button>
        <el-button type="danger" :disabled="multipleSelection.length === 0" @click="handleBatchDelete">
          删除
        </el-button>
      </div>
      <el-table
        :data="tableData"
        row-key="driftId"
        style="width: 100%"
        v-loading="loading"
        height="350px"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" fixed="left" />
        <el-table-column fixed="left" type="index" label="序号" width="60" />
        <el-table-column prop="driftName" label="巷道名称" width="200" />
        <el-table-column prop="driftCode" label="巷道编码" width="160" />
        <el-table-column prop="warehouseName" label="所属库房" width="220" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.driftState === 1 ? 'success' : 'danger'">
              {{ row.driftState === 1 ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="driftOrderBy" label="排序" width="80" />
        <el-table-column
          prop="driftDesc"
          label="备注"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column prop="createor" label="创建人" width="120" />
        <el-table-column prop="createrTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createrTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="240">
          <template #default="{ row }">
            <el-button link size="small" type="success"  @click="openEditDialog(row)">修改</el-button>
            <el-button link size="small" type="warning"  @click="openDetailDialog(row)">详情</el-button>
            <el-button link size="small" type="danger"  @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  <!-- 分页 -->
    <el-card class="action-card">
      <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="pageinfo.pageIndex"
        v-model:page-size="pageinfo.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="pageinfo.total"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    </el-card>
   
    

    <!-- 添加/编辑/详情巷道弹框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogMode === 'add' ? '添加巷道' : dialogMode === 'edit' ? '编辑巷道' : '巷道详情'" 
      width="600px" 
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="巷道名称" prop="driftName">
          <el-input 
            v-model="form.driftName" 
            placeholder="请输入巷道名称" 
            clearable 
            :disabled="dialogMode === 'detail'"
          />
        </el-form-item>
        <el-form-item label="巷道编码" prop="driftCode">
          <el-input 
            v-model="form.driftCode" 
            :placeholder="dialogMode === 'add' ? '点击自动生成按钮获取编号' : '请输入巷道编码'" 
            :readonly="dialogMode === 'add'"
            :disabled="dialogMode === 'detail'"
          >
            <template #append v-if="dialogMode === 'add'">
              <el-button @click="generateDriftCode" :loading="generatingCode">自动生成</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="所属库房" prop="warehouseId">
          <el-select
            v-model="form.warehouseId"
            placeholder="请选择"
            filterable
            clearable
            style="width: 100%"
            :loading="warehouseLoading"
            :disabled="dialogMode === 'detail'"
          >
            <el-option
              v-for="item in warehouseOptions"
              :key="item.warehouseId"
              :label="item.warehouseName"
              :value="item.warehouseId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="driftState">
          <el-radio-group v-model="form.driftState" :disabled="dialogMode === 'detail'">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="2">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序号" prop="driftOrderBy">
          <el-input-number 
            v-model="form.driftOrderBy" 
            :min="0" 
            style="width: 100%" 
            :disabled="dialogMode === 'detail'"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.driftDesc"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
            maxlength="500"
            show-word-limit
            :disabled="dialogMode === 'detail'"
          />
        </el-form-item>
        <el-form-item v-if="dialogMode === 'detail'" label="创建人">
          <el-input v-model="form.createor" readonly />
        </el-form-item>
        <el-form-item v-if="dialogMode === 'detail'" label="创建时间">
          <el-input :value="formatDate(form.createrTime)" readonly />
        </el-form-item>
        <el-form-item v-if="dialogMode === 'detail' && form.updater" label="修改人">
          <el-input v-model="form.updater" readonly />
        </el-form-item>
        <el-form-item v-if="dialogMode === 'detail' && form.updateTime" label="修改时间">
          <el-input :value="formatDate(form.updateTime)" readonly />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button 
            v-if="dialogMode !== 'detail'" 
            type="primary" 
            @click="handleSave" 
            :loading="saving"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import myaxios from '@/http/MyAxios'

// 查询条件
const searchForm = reactive({
  driftName: '', // 巷道名称
})

// 分页信息
const pageinfo = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
})

// 列表数据
const tableData = ref<any[]>([])
const loading = ref(false)
const multipleSelection = ref<any[]>([])

// 弹框相关
const dialogVisible = ref(false)
const formRef = ref<FormInstance>()
const saving = ref(false)
const dialogMode = ref<'add' | 'edit' | 'detail'>('add') // 弹框模式：新增、编辑、详情

// 表单数据
const form = reactive({
  driftId: null as number | null,
  driftName: '',
  driftCode: '',
  warehouseId: null as number | null,
  driftState: 1, // 默认启用
  driftOrderBy: 2, // 默认排序号2
  driftDesc: '',
  createor: '',
  createrTime: null as Date | string | null,
  updater: '',
  updateTime: null as Date | string | null,
})

// 表单验证规则
const rules: FormRules = {
  driftName: [{ required: true, message: '请输入巷道名称', trigger: 'blur' }],
  driftCode: [{ required: true, message: '请输入巷道编码', trigger: 'blur' }],
  warehouseId: [{ required: true, message: '请选择所属库房', trigger: 'change' }],
  driftState: [{ required: true, message: '请选择状态', trigger: 'change' }],
  driftOrderBy: [{ required: true, message: '请输入排序号', trigger: 'blur' }],
}

// 仓库选项
const warehouseOptions = ref<Array<{ warehouseId: number; warehouseName: string }>>([])
const warehouseLoading = ref(false)

// 编号生成相关
const generatingCode = ref(false)

const formatDate = (val?: string | Date | null) => {
  if (!val) return '-'
  return dayjs(val).format('YYYY-MM-DD HH:mm:ss')
}

// 获取巷道列表（分页）
const getDriftList = () => {
  loading.value = true
  myaxios({
    url: '/api/Drift/GetDriftPage',
    method: 'get',
    params: {
      Pageindex: pageinfo.pageIndex,
      PageSize: pageinfo.pageSize,
      driftName: searchForm.driftName,
    },
  })
    .then(res => {
      const data = res.data?.data
      // 后端分页结构与单位、货品列表保持一致：data.data 为列表，data.listCount 为总数
      tableData.value = data?.data || []
      pageinfo.total = data?.listCount || 0
    })
    .catch(err => {
      console.error('获取巷道列表失败:', err)
      ElMessage.error('获取巷道列表失败')
    })
    .finally(() => {
      loading.value = false
    })
}

// 查询
const handleSearch = () => {
  pageinfo.pageIndex = 1
  getDriftList()
}

// 重置
const handleReset = () => {
  searchForm.driftName = ''
  pageinfo.pageIndex = 1
  getDriftList()
}

// 分页尺寸变化
const handleSizeChange = (val: number) => {
  pageinfo.pageSize = val
  pageinfo.pageIndex = 1
  getDriftList()
}

// 页码变化
const handleCurrentChange = (val: number) => {
  pageinfo.pageIndex = val
  getDriftList()
}

// 打开新增弹框
const openDialog = () => {
  dialogMode.value = 'add'
  resetForm()
  loadWarehouses()
  dialogVisible.value = true
}

// 打开编辑弹框
const openEditDialog = async (row: any) => {
  dialogMode.value = 'edit'
  resetForm()
  loadWarehouses()
  
  // 加载巷道详情
  try {
    const res = await myaxios({
      url: `/api/Drift/GetDriftDetail`,
      method: 'get',
      params: { driftId: row.driftId },
    })
    
    if (res.data?.code === 200 && res.data?.data) {
      const data = res.data.data
      form.driftId = data.driftId
      form.driftName = data.driftName || ''
      form.driftCode = data.driftCode || ''
      form.warehouseId = data.warehouseId || null
      form.driftState = data.driftState || 1
      form.driftOrderBy = data.driftOrderBy || 0
      form.driftDesc = data.driftDesc || ''
    } else {
      ElMessage.error(res.data?.message || '获取巷道详情失败')
      return
    }
  } catch (error: any) {
    console.error('获取巷道详情失败:', error)
    ElMessage.error('获取巷道详情失败，请稍后重试')
    return
  }
  
  dialogVisible.value = true
}

// 打开详情弹框
const openDetailDialog = async (row: any) => {
  dialogMode.value = 'detail'
  resetForm()
  loadWarehouses()
  
  // 加载巷道详情
  try {
    const res = await myaxios({
      url: `/api/Drift/GetDriftDetail`,
      method: 'get',
      params: { driftId: row.driftId },
    })
    
    if (res.data?.code === 200 && res.data?.data) {
      const data = res.data.data
      form.driftId = data.driftId
      form.driftName = data.driftName || ''
      form.driftCode = data.driftCode || ''
      form.warehouseId = data.warehouseId || null
      form.driftState = data.driftState || 1
      form.driftOrderBy = data.driftOrderBy || 0
      form.driftDesc = data.driftDesc || ''
      form.createor = data.createor || ''
      form.createrTime = data.createrTime || null
      form.updater = data.updater || ''
      form.updateTime = data.updateTime || null
    } else {
      ElMessage.error(res.data?.message || '获取巷道详情失败')
      return
    }
  } catch (error: any) {
    console.error('获取巷道详情失败:', error)
    ElMessage.error('获取巷道详情失败，请稍后重试')
    return
  }
  
  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  form.driftId = null
  form.driftName = ''
  form.driftCode = ''
  form.warehouseId = null
  form.driftState = 1
  form.driftOrderBy = 2
  form.driftDesc = ''
  form.createor = ''
  form.createrTime = null
  form.updater = ''
  form.updateTime = null
  formRef.value?.clearValidate()
}

// 加载仓库列表
const loadWarehouses = async () => {
  if (warehouseLoading.value) return
  warehouseLoading.value = true
  try {
    const res = await myaxios({
      url: '/api/Warehousing/GetWarehouse',
      method: 'get',
    })
    if (res.data?.code === 200 || res.data?.success) {
      const warehouses = res.data.data || []
      warehouseOptions.value = warehouses.map((item: any) => ({
        warehouseId: item.warehouseId,
        warehouseName: item.warehouseName,
      }))
    } else {
      ElMessage.error(res.data?.message || '获取仓库列表失败')
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    ElMessage.error('获取仓库列表失败，请稍后重试')
  } finally {
    warehouseLoading.value = false
  }
}

// 编号生成相关函数
const TIME_SEGMENT_ORDER = ['YYYY', 'YY', 'MM', 'DD', 'HH', 'MI', 'SS']
const pad = (n: number, len = 2) => `${n}`.padStart(len, '0')

const buildCodeFromRule = (rule: any) => {
  const now = new Date()
  const segments = (rule?.timeRule || '')
    .split(',')
    .map((s: string) => s.trim().toUpperCase())
    .filter(Boolean)
    .sort((a: string, b: string) => {
      const indexA = TIME_SEGMENT_ORDER.indexOf(a)
      const indexB = TIME_SEGMENT_ORDER.indexOf(b)
      if (indexA === -1 && indexB === -1) return 0
      if (indexA === -1) return 1
      if (indexB === -1) return -1
      return indexA - indexB
    })
  const datePart = segments
    .map((seg: string) => {
      switch (seg) {
        case 'YYYY': return String(now.getFullYear())
        case 'YY': return String(now.getFullYear()).slice(-2)
        case 'MM': return pad(now.getMonth() + 1)
        case 'DD': return pad(now.getDate())
        case 'HH': return pad(now.getHours())
        case 'MI': return pad(now.getMinutes())
        case 'SS': return pad(now.getSeconds())
        default: return ''
      }
    })
    .join('')
  const seq = '1'.padStart(rule?.serialLength || 3, '0')
  return `${rule?.codePrefix || ''}${datePart}${seq}`
}

const requestDriftCode = async () => {
  try {
    const res = await myaxios.get('/api/Number/GenerateNumber', {
      params: { targetCode: 'Drift', targetName: '巷道' }
    })
    if (res?.data?.code === 200 && res?.data?.data) {
      return String(res.data.data)
    }
    throw new Error(res?.data?.message || '生成编号失败')
  } catch (err) {
    console.warn('[drift] GenerateNumber 接口不可用，尝试规则生成', err)
    const ruleRes = await myaxios.get('/api/Number/QueryNumberingRules', {
      params: { targetCode: 'Drift', targetName: '巷道' }
    })
    const list = Array.isArray(ruleRes?.data?.data) ? ruleRes.data.data : []
    if (list.length > 0) {
      return buildCodeFromRule(list[0])
    }
    throw new Error('未找到对应的编号规则，请先配置编号规则')
  }
}

const generateDriftCode = async () => {
  generatingCode.value = true
  try {
    form.driftCode = await requestDriftCode()
    ElMessage.success('编号生成成功')
  } catch (err: any) {
    ElMessage.error(err?.message || '生成编号失败')
  } finally {
    generatingCode.value = false
  }
}

// 保存巷道（新增或编辑）
const handleSave = async () => {
  if (!formRef.value) return
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return

  // 新增模式下，如果用户没有输入编码，自动生成
  if (dialogMode.value === 'add' && !form.driftCode) {
    try {
      await generateDriftCode()
      // 如果生成失败，停止保存
      if (!form.driftCode) {
        ElMessage.warning('请先生成巷道编码')
        return
      }
    } catch (error) {
      ElMessage.warning('生成巷道编码失败，请稍后重试')
      return
    }
  }

  saving.value = true
  try {
    const url = dialogMode.value === 'add' ? '/api/Drift/CreateDrift' : '/api/Drift/UpdateDrift'
    const data = {
      driftId: dialogMode.value === 'edit' ? form.driftId : undefined,
      driftName: form.driftName,
      driftCode: form.driftCode,
      warehouseId: form.warehouseId,
      driftState: form.driftState,
      driftOrderBy: form.driftOrderBy,
      driftDesc: form.driftDesc || '',
    }

    const res = await myaxios({
      url,
      method: 'post',
      data,
    })

    if (res.data?.code === 200) {
      ElMessage.success(res.data?.message || (dialogMode.value === 'add' ? '添加巷道成功' : '更新巷道成功'))
      dialogVisible.value = false
      getDriftList()
    } else {
      ElMessage.error(res.data?.message || (dialogMode.value === 'add' ? '添加巷道失败' : '更新巷道失败'))
    }
  } catch (error: any) {
    console.error(`${dialogMode.value === 'add' ? '添加' : '更新'}巷道失败:`, error)
    const errorMsg =
      error?.response?.data?.message ||
      error?.message ||
      `${dialogMode.value === 'add' ? '添加' : '更新'}巷道失败，请稍后重试`
    ElMessage.error(errorMsg)
  } finally {
    saving.value = false
  }
}

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  multipleSelection.value = selection
}

// 单个删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    '确认删除这条巷道信息吗？',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      myaxios({
        url: '/api/Drift/DeleteDrift',
        method: 'delete',
        params: { driftId: row.driftId },
      })
        .then(res => {
          if (res.data?.code === 200) {
            ElMessage.success(res.data?.message || '删除成功')
            getDriftList()
          } else {
            ElMessage.error(res.data?.message || '删除失败')
          }
        })
        .catch(error => {
          console.error('删除巷道失败:', error)
          ElMessage.error('删除巷道失败，请稍后重试')
        })
    })
    .catch(() => {
      // 用户取消删除
    })
}

// 批量删除
const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的巷道')
    return
  }

  ElMessageBox.confirm(
    `确认删除选中的 ${multipleSelection.value.length} 条巷道信息吗？`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      const ids = multipleSelection.value.map(item => item.driftId)
      myaxios({
        url: '/api/Drift/DeleteDrifts',
        method: 'post',
        data: { ids },
      })
        .then(res => {
          if (res.data?.code === 200) {
            ElMessage.success(res.data?.message || '批量删除成功')
            multipleSelection.value = []
            getDriftList()
          } else {
            ElMessage.error(res.data?.message || '批量删除失败')
          }
        })
        .catch(error => {
          console.error('批量删除巷道失败:', error)
          ElMessage.error('批量删除巷道失败，请稍后重试')
        })
    })
    .catch(() => {
      // 用户取消删除
    })
}

onMounted(() => {
  getDriftList()
})
</script>

<style scoped>
.drift-page {
  padding: 10px;
}

.search-card,
.action-card,
.table-card {
  margin-bottom: 15px;
}

.dialog-footer {
  text-align: right;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>


